import javax.naming.*;
import javax.servlet.http.*;
import javax.sql.DataSource;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;

public class DatabaseConnection extends HttpServlet {
    private static final long serialVersionUID = -958889122880937111L;

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        try {
            // 获取初始化的上下文对象
            InitialContext initContext = new InitialContext();
            // 获取配置的数据源的名称的相应数据源对象
            DataSource source = (DataSource) initContext.lookup("java:/comp/env/connection");
            // 获取数据源连接
            Connection c = source.getConnection();
            if (c != null) {
                out.print("连接数据库成功");
                c.close();
            } else {
                out.println("连接数据库失败");
            }
        } catch (NamingException | SQLException e) {
            e.printStackTrace();
        }
    }
}
